package com.bsoft.gol.hbs.message.sendMsg;

import hcn.bean.SendMsgDTO;
import hcn.util.BaseResponse;
import org.springframework.stereotype.Service;

/**
 * @description: 微信公众号的消息发送实现
 * @author: zhengcb10708
 * @create: 2020-10-09 17:38
 **/
@Service
public class WeChatSendMsgService extends AbstractSendMsgServiceImpl{
    @Override
    protected boolean isDoSendMsg() {
        return false;
    }

    @Override
    protected BaseResponse doSendMsg(SendMsgDTO sendMsgDTO, String content) {
        return null;
    }

    @Override
    protected BaseResponse doSendPushMsg(SendMsgDTO sendMsgDTO, String content) {
        return null;
    }

    @Override
    protected String getName() {
        return null;
    }

    @Override
    public String getMsgType() {
        return null;
    }
    /*private static Logger logger = LoggerFactory.getLogger(WeChatSendMsgService.class);
    @Value("${wxMpAppId}")
    private String wxMpAppId;
    private WechatMsgManager wechatMsgManager;
    private MsgPushTaskDao msgPushTaskDao;
    private MsgPushTaskDetailDao msgPushTaskDetailDao;

    public WechatMsgManager getWechatMsgManager() {
        return wechatMsgManager;
    }

    public String getWxMpAppId() {
        return wxMpAppId;
    }

    public void setWxMpAppId(String wxMpAppId) {
        this.wxMpAppId = wxMpAppId;
    }

    public MsgPushTaskDao getMsgPushTaskDao() {
        return msgPushTaskDao;
    }

    public void setMsgPushTaskDao(MsgPushTaskDao msgPushTaskDao) {
        this.msgPushTaskDao = msgPushTaskDao;
    }

    public MsgPushTaskDetailDao getMsgPushTaskDetailDao() {
        return msgPushTaskDetailDao;
    }

    public void setMsgPushTaskDetailDao(MsgPushTaskDetailDao msgPushTaskDetailDao) {
        this.msgPushTaskDetailDao = msgPushTaskDetailDao;
    }

    public void setWechatMsgManager(WechatMsgManager wechatMsgManager) {
        this.wechatMsgManager = wechatMsgManager;
    }

    *//**
     * @Describe: 判断是否进行发消息操作-主要进行配置参数的校验
     * @Param: []
     * @Return: boolean
     * @Author: zhengcb10708
     * @Date: 2020/10/9 17:39
     *//*
    @Override
    protected boolean isDoSendMsg() {
        return true;
    }

    *//**
     * @Describe: 发送消息具体实现
     * @Param: [sendMsgDTO, content]
     * @Return: BaseResponse
     * @Author: zhengcb10708
     * @Date: 2020/10/9 17:40
     *//*
    @Override
    protected BaseResponse doSendMsg(SendMsgDTO sendMsgDTO, String content) {
        BaseResponse baseResponse = new BaseResponse();
        Map<String, String> text = new HashMap<>();
        try{
            if(CommonUtils.isNull(sendMsgDTO.getMsgServiceType())){
                logger.error("微信发送服务类型未传");
                baseResponse.setCode(ResultCode.ERROR);
                baseResponse.setMessage("微信发送服务类型未传");
                return baseResponse;
            }
            if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.WECHATMSGMANAGER.getCode().equals(sendMsgDTO.getMsgServiceType())){
                //通过lamada表达式将map里值为null或者空的清除
                sendMsgDTO.getWeChatTextMap().entrySet().removeIf(entry -> CommonUtils.isEmpty(entry.getValue()));
                if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatUserIdList())){
                    for(String userId:sendMsgDTO.getWeChatUserIdList()){
                        wechatMsgManager.sentWeChatMsg(sendMsgDTO.getWeChatTextMap(),userId,sendMsgDTO.getWeChatTplCode());
                    }
                }
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMessage("消息发送成功");
            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.SENDWXMSGSERVICE.getCode().equals(sendMsgDTO.getMsgServiceType())){
                //通过lamada表达式将map里值为null或者空的清除
                sendMsgDTO.getWeChatTextMap().entrySet().removeIf(entry -> CommonUtils.isEmpty(entry.getValue()));
                if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatUserIdList())){
                    for(String userId:sendMsgDTO.getWeChatUserIdList()){

                        PushWeChatMsgEvent a = new PushWeChatMsgEvent();
                        a.setTemplateId(sendMsgDTO.getWeChatTplCode());
                        a.setTemplateTagsReplaceList(sendMsgDTO.getWeChatTextMap());
                        a.setAppId(sendMsgDTO.getAppId());
                        a.setUserId(userId);
                        if(CommonUtils.isNotNull(sendMsgDTO.getTypeEnum())){
                            a.setTypeEnum(AppIdTypeEnum.wx);
                        }
                        a.setOutAppType(sendMsgDTO.getOutAppType());
                        Client.rpcInvoke("hcn.wxNotificationService","sentWeChatMsg",a);
                    }
                }
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMessage("消息发送成功");
            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.WXSENDWXMESSAGE.getCode().equals(sendMsgDTO.getMsgServiceType())){
                //通过lamada表达式将map里值为null或者空的清除
                sendMsgDTO.getWeChatTextMap().entrySet().removeIf(entry -> CommonUtils.isEmpty(entry.getValue()));
                if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatUserIdList())){
                    for(String userId:sendMsgDTO.getWeChatUserIdList()){
                        WeChatMsgVo msg = new WeChatMsgVo();
                        msg.setUserId(userId);
                        msg.setTemplateId(sendMsgDTO.getWeChatTplCode());
                        msg.setText(sendMsgDTO.getWeChatTextMap());
                        Client.rpcInvoke("hcn.wxNotificationService","sendWxMessage",msg);
                    }
                }

            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.SENDIMMSGTOWECHAT.getCode().equals(sendMsgDTO.getMsgServiceType())){
                sendMsgDTO.getWeChatTextMap().entrySet().removeIf(entry -> CommonUtils.isEmpty(entry.getValue()));
                HashMap<String, String> params = new HashMap<>();
                for (Map.Entry<String, String> entry : sendMsgDTO.getWeChatTextMap().entrySet()) {
                    params.put(entry.getValue(), entry.getKey());
                }
                ImChatDto imChatDto = new ImChatDto();
                imChatDto.setMpiId(sendMsgDTO.getMsgId());
                imChatDto.setName(sendMsgDTO.getName());
                imChatDto.setParams(params);
                imChatDto.setUserId(sendMsgDTO.getUserId());
                Client.rpcInvoke("hcn.sendWxMsgService","sendImMsgToWeChat",imChatDto);
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMessage("消息发送成功");
            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.SENDWXMESSAGE.getCode().equals(sendMsgDTO.getMsgServiceType())){
                sendMsgDTO.getWeChatTextMap().entrySet().removeIf(entry -> CommonUtils.isEmpty(entry.getValue()));
                WeChatMsgVo msg = new WeChatMsgVo();
                msg.setUserId(sendMsgDTO.getUserId());
                msg.setTemplateId(sendMsgDTO.getWeChatTplCode());
                msg.setText(sendMsgDTO.getWeChatTextMap());
                Client.rpcInvoke("hcn.sendWxMsgService","sendWxMessage",msg);
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMessage("消息发送成功");
            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatTextMap())&& MsgServiceTypeEnum.WECHATMSGMQSERVICE_SENTWECHATMSGLIST.getCode().equals(sendMsgDTO.getMsgServiceType())){
                List<WeChatMsgVo> msgs = new ArrayList<WeChatMsgVo>();
                if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatUserIdList())){
                    for(String userId:sendMsgDTO.getWeChatUserIdList()){
                        WeChatMsgVo msg = new WeChatMsgVo();
                        msg.setUserId(userId);
                        msg.setTemplateId(sendMsgDTO.getWeChatTplCode());//通知模板
                        if(CommonUtils.isNotEmpty(sendMsgDTO.getMiniprogram())){
                            msg.setMiniprogram(sendMsgDTO.getMiniprogram());
                        }
                        msg.setText(sendMsgDTO.getWeChatTextMap());
                        msgs.add(msg);
                    }
                }
                Client.rpcInvoke("hcn.weChatMsgMqService", "sentWeChatMsgList", msgs);
            }

        }catch (Exception e){
            logger.error("执行方法WeChatSendMsgService.doSendMsg出错,原因:"+e.getMessage());
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMessage(e.getMessage());
            return baseResponse;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return baseResponse;
    }
    *//**
     * @Describe: 推送手工消息的具体实现
     * @Param: [sendMsgDTO, content]
     * @Return: BaseResponse
     * @Author: zhengcb10708
     * @Date: 2021/9/8 10:51
     *//*
    @Override
    protected BaseResponse doSendPushMsg(SendMsgDTO sendMsgDTO, String content) {
        BaseResponse baseResponse=new BaseResponse();
        logger.info("执行WeChatSendMsgService。doSendPushMsg start");
        try {
            if(CommonUtils.isNotEmpty(sendMsgDTO.getWeChatUserIdList())){
                for(String userId:sendMsgDTO.getWeChatUserIdList()){
                    List<UcUserBindResult> bindResult = msgPushTaskDetailDao.getByUidAndTypeAndAppId(userId, "wx", wxMpAppId);
                    if(CommonUtils.isNotEmpty(bindResult)){
                        //获取微信公众号access_tocken
                        String accessToken = (String) Client.rpcInvoke("hcn.weChatService", "getAccessToken", wxMpAppId);
                        JSONObject parameters = new JSONObject();
                        parameters.put("touser", bindResult.get(0).getOutUid());
                        parameters.put("msgtype", "text");
                        JSONObject textSub = new JSONObject();
                        textSub.put("content", content);
                        parameters.put("text", textSub);
                        baseResponse=WeChatMessageApiUtil.sendtextMessageToUser(parameters.toJSONString(),accessToken);
                        if(ResultCode.SUCCESS==baseResponse.getCode()){
                            updateMsgPushTaskDetail(sendMsgDTO,ResultCode.SUCCESS);
                        }else {//发送失败
                            updateMsgPushTaskDetail(sendMsgDTO,ResultCode.ERROR);
                        }
                    }else{
                        updateMsgPushTaskDetail(sendMsgDTO,ResultCode.ERROR);
                        baseResponse.setMessage("用户未绑定公众号");
                        baseResponse.setCode(ResultCode.ERROR);
                    }
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            baseResponse.setCode(ResultCode.ERROR);
        }
        return baseResponse;
    }

    *//**
     * @Describe: 得到具体实现类的名称
     * @Param: []
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2020/10/9 17:42
     *//*
    @Override
    protected String getName() {
        return MsgType.WECHAT.getMsgTypeValue();
    }
    *//**
     * @Describe: 获取消息类型
     * @Param: []
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2020/10/9 17:42
     *//*
    @Override
    public String getMsgType() {
        return MsgType.WECHAT.getMsgTypeKey();
    }

    private void updateMsgPushTaskDetail(SendMsgDTO sendMsgDTO, int flag){
        try {
            Map<String, String> extras = sendMsgDTO.getExtras();
            if(CommonUtils.isNotEmpty(extras)){
                Long msgPushTaskId=Long.parseLong(extras.get("msgPushTaskId"));
                String userId=extras.get("userId");
                if(CommonUtils.isNotEmpty(msgPushTaskId)&& hcn.utils.CommonUtils.isNotEmpty(userId)){
                    List<MsgPushTaskDetail> list=msgPushTaskDetailDao.findMsgPushTaskDetailList(userId,msgPushTaskId);
                    if(CommonUtils.isNotEmpty(list)){
                        Timestamp nowTime = new Timestamp(System.currentTimeMillis());
                        String msgType=list.get(0).getMsgType();
                        String successMsgType=list.get(0).getSuccessMsgType()==null?"":list.get(0).getSuccessMsgType();
                        String failMsgType=list.get(0).getFailMsgType()==null?"":list.get(0).getFailMsgType();
                        String failReason=list.get(0).getFailReason()==null?"":list.get(0).getFailReason();
                        Byte pushStatus=list.get(0).getPushStatus();
                        //推送成功
                        if(ResultCode.SUCCESS==flag){
                            //successMsgType 添加 WECHAT 发送成功的标志
                            if(CommonUtils.isEmpty(successMsgType)){
                                successMsgType= MsgType.WECHAT.getMsgTypeKey();
                            }else{
                                if(!successMsgType.contains(MsgType.WECHAT.getMsgTypeKey())){
                                    successMsgType+=","+MsgType.WECHAT.getMsgTypeKey();
                                }
                            }
                            // failMsgType 去掉WECHAT发送失败的标志
                            if(CommonUtils.isNotEmpty(failMsgType)&&failMsgType.contains(MsgType.WECHAT.getMsgTypeKey())
                                    &&failMsgType.contains(MsgType.APP_PUSH.getMsgTypeKey())){
                                failMsgType=MsgType.APP_PUSH.getMsgTypeKey();
                            }else if(CommonUtils.isNotEmpty(failMsgType)&&failMsgType.contains(MsgType.APP_PUSH.getMsgTypeKey())){
                                failMsgType="";
                            }
                            //发送成功后，去掉微信发送的失败原因
                            if(CommonUtils.isNotEmpty(failReason)&&(failReason.contains(MsgPushFaileTypeEnum.NOTONLINE.getCode())
                                    ||failReason.contains(MsgPushFaileTypeEnum.NONEEDSEND.getCode())
                                    ||failReason.contains(MsgPushFaileTypeEnum.NOTGETMSGID.getCode()))
                                    &&failReason.contains(MsgPushFaileTypeEnum.WECHATFAILE.getCode())){
                                failReason=failReason.replaceAll(","+MsgPushFaileTypeEnum.WECHATFAILE.getCode(),"");
                                failReason=failReason.replaceAll(MsgPushFaileTypeEnum.WECHATFAILE.getCode()+",","");
                            }else if(CommonUtils.isNotEmpty(failReason)&&!(failReason.contains(MsgPushFaileTypeEnum.NOTONLINE.getCode())
                                    ||failReason.contains(MsgPushFaileTypeEnum.NONEEDSEND.getCode())
                                    ||failReason.contains(MsgPushFaileTypeEnum.NOTGETMSGID.getCode()))
                                    &&failReason.contains(MsgPushFaileTypeEnum.WECHATFAILE.getCode())){
                                failReason="";
                            }
                            pushStatus=MsgPushStatusEnum.PUSHSUCCEEDED.getStatus();

                            msgPushTaskDetailDao.updateMsgPushTaskDetail(successMsgType,failMsgType,failReason,pushStatus,
                                    nowTime,nowTime,userId,msgPushTaskId);
                            //更新消息推送任务表
                            updateMsgPushTask(msgPushTaskId);
                        }else if(ResultCode.ERROR==flag){//推送失败

                            // failMsgType 添加APP_PUSH发送失败的标志
                            if(CommonUtils.isEmpty(failMsgType)){
                                failMsgType= MsgType.WECHAT.getMsgTypeKey();
                            }else{
                                if(!failMsgType.contains(MsgType.APP_PUSH.getMsgTypeKey())){
                                    failMsgType+=","+MsgType.APP_PUSH.getMsgTypeKey();
                                }
                            }
                            //添加失败原因
                            if(CommonUtils.isEmpty(failReason)){
                                failReason=MsgPushFaileTypeEnum.WECHATFAILE.getCode();
                            }else{
                                if(CommonUtils.isNotEmpty(failReason)&&(!failReason.contains(MsgPushFaileTypeEnum.WECHATFAILE.getCode()))){
                                    failReason += ","+MsgPushFaileTypeEnum.WECHATFAILE.getCode();
                                }
                            }
                            //如果app已推送成功，则任务详情视为成功,不改变推送状态
                            if(!String.valueOf(MsgPushStatusEnum.PUSHSUCCEEDED.getStatus()).equals(String.valueOf(pushStatus))){
                                pushStatus=MsgPushStatusEnum.FAILED.getStatus();
                            }
                            msgPushTaskDetailDao.updateMsgPushTaskDetail(successMsgType,failMsgType,failReason,pushStatus,
                                    nowTime,nowTime,userId,msgPushTaskId);
                            //更新消息推送任务表
                            updateMsgPushTask(msgPushTaskId);
                        }
                    }
                }
            }
        } catch (NumberFormatException e) {
            logger.error("updateMsgPushTaskDetail failed,cause:"+e.getMessage());
            e.printStackTrace();
        }
    }
    private void updateMsgPushTask(Long msgPushTaskId){
        *//*手工推送消息结束时间*//*
        Timestamp endTime = new Timestamp(System.currentTimeMillis());
        MsgPushTask msgPushTask= msgPushTaskDao.getMsgPushTaskByTaskId(msgPushTaskId);
        //获取推送成功的人数
        Long count=msgPushTaskDetailDao.getMsgPushTaskCount(msgPushTaskId);
        msgPushTask.setSuccessHeadCount(count.intValue());
        msgPushTask.setEndPushTime(endTime);
        msgPushTask.setLastModifyTime(endTime);
        msgPushTaskDao.update(msgPushTask);
    }*/
}
